package com.util;

import com.sap.conn.jco.JCoDestination;
import com.sap.conn.jco.JCoDestinationManager;
import com.sap.conn.jco.JCoException;
import com.sap.conn.jco.JCoFunction;
import com.sap.conn.jco.JCoParameterList;
import com.sap.conn.jco.JCoTable;

import java.io.*;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.StringTokenizer;

public class GetSapConnRk {
    public static String ABAP_AS_POOLED = "ABAP_AS_WITH_POOLRK1";

    private static void createDataFile() throws IOException {
        Properties proes = new Properties();
        File file = new File(JarPathUtil.getJarPath()+File.separator+"Rkqs.properties");
        FileInputStream inputStream = new FileInputStream(file);
        proes.load(inputStream);

        Properties properties = new Properties();
        properties.setProperty("jco.client.ashost", proes.getProperty("jco.client.ashost"));
        properties.setProperty("jco.client.sysnr", proes.getProperty("jco.client.sysnr"));
        properties.setProperty("jco.client.client", proes.getProperty("jco.client.client"));
        properties.setProperty("jco.client.user", proes.getProperty("jco.client.user"));
        properties.setProperty("jco.client.passwd", proes.getProperty("jco.client.passwd"));
        properties.setProperty("jco.client.lang", proes.getProperty("jco.client.lang"));
        properties.setProperty("jco.client.codepage", proes.getProperty("jco.client.codepage"));
        String name = ABAP_AS_POOLED;
        String suffix = "jcoDestination";
        File cfg = new File(String.valueOf(name) + "." + suffix);
        if (!cfg.exists())
            try {
                FileOutputStream fos = new FileOutputStream(cfg, false);
                properties.store(fos, "for tests only !");
                fos.close();
            } catch (Exception exception) {
                throw new RuntimeException("Unable to create the destination file " + cfg.getName(), exception);
            }
    }

    public static JCoDestination getJcoConnection() throws IOException {
        createDataFile();
        try {
            return JCoDestinationManager.getDestination(ABAP_AS_POOLED);
        } catch (JCoException exception) {
            exception.printStackTrace();
            return null;
        }
    }

    public void startSyTask() {
        JCoDestination jCoDestination = null;
        JCoFunction function = null;
        try {
            jCoDestination = getJcoConnection();
            String interfacename = "ZMM_C1_STOCK";
            function = jCoDestination.getRepository().getFunctionTemplate(interfacename).getFunction();
            JCoParameterList input = function.getImportParameterList();
            LocalDate today = LocalDate.now();
            today = today.minusMonths(1L);
            DateTimeFormatter formatteryear = DateTimeFormatter.ofPattern("yyyy");
            DateTimeFormatter formattermonth = DateTimeFormatter.ofPattern("MM");
            String year = formatteryear.format(today);
            String month = formattermonth.format(today);
            input.setValue("IV_MJAHR", year);
            input.setValue("IV_PERIOD", month);
            if (function == null)
                throw new RuntimeException("get function not found in sap");
            function.execute(jCoDestination);
            List<String> tableDe = new ArrayList<>();
            StringBuffer colums = new StringBuffer();
            colums.append("TB_MMSTOCK:");
            colums.append("C1.warehousing:");
            colums.append("MJAHR,");
            colums.append("MONAT,");
            colums.append("PRCTR,");
            colums.append("MFRGR,");
            colums.append("MENGE");
            StringBuffer colums2 = new StringBuffer();
            colums2.append("TB_MFRGR:");
            colums2.append("C1.mt_tans:");
            colums2.append("MFRGR,");
            colums2.append("BEZEI");
            tableDe.add(colums.toString());
            tableDe.add(colums2.toString());
            Iterator<String> iterator = tableDe.iterator();
            while (iterator.hasNext()) {
                String tableDesc = iterator.next();
                String[] desc = tableDesc.split(":");
                String JCtable = desc[0];
                String table = desc[1];
                String colus = desc[2];
                JCoTable table2 = function.getTableParameterList().getTable(JCtable);
                String[] cols = colus.toString().split(",");
                StringTokenizer st = new StringTokenizer(colus.toString(), ",", false);
                String values;
                for (values = colus.toString(); st.hasMoreTokens(); values = values.replaceFirst(st.nextToken(), "?"));
                String sql = "INSERT INTO " + table + "(" + colus.toString() + ") VALUES(" + values + ")";
                JdbcConn jdbcConn = new JdbcConn();
                if ("C1.warehousing".equals(table)) {
                    jdbcConn.executesql("delete from " + table + " where MJAHR = '" + year + "' and MONAT = '" + month + "'");
                } else {
                    jdbcConn.executesql("truncate table " + table);
                }
                jdbcConn.insert(table2, sql, cols, interfacename, table);
                System.out.println(table2.getNumRows());
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }
}
